package com.qunar.flight.myserver;

import java.io.IOException;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.log4j.Logger;

public class Dispatcher1 implements Dispatcher {
	static Logger logger = Logger.getLogger(Dispatcher1.class);
	Selector sel = null;

	public Dispatcher1(Selector sel) throws IOException {
		this.sel = sel;
	}

	ReentrantLock l = new ReentrantLock();

	public void run() {
		for (;;) {
			try {
				sel.select();
				Set<SelectionKey> set = sel.selectedKeys();
				Iterator<SelectionKey> i = set.iterator();
				if (0 == set.size()) {
					continue;
				}
				logger.info("selected的大小为" + set.size() + "，接着进行相应次数的处理");
				l.lock();
				try {
					for (; i.hasNext();) {
						SelectionKey sk = (SelectionKey) i.next();
						logger.info("事件:" + sk.interestOps() + ":" + sk);
						i.remove();
						Handler h = (Handler) sk.attachment();
						logger.info("绑定的handler为" + h);
						h.setSk(sk);
						h.run();
						// new Thread(h).start();
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					l.unlock();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public void register(SelectableChannel ch, int ops, Handler h)
			throws IOException {
		l.lock();
		try {
			sel.wakeup();
			SelectionKey sk = ch.register(sel, ops, h);
			logger.info("注册感兴趣的事件：" + sk.interestOps() + "***" + ops);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			l.unlock();
		}
	}
}
